<template>
  <div>
    <!-- step one -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-card
        :bordered="false"
        style="margin-left: 16px;margin-right: 16px;margin-top: 16px;"
      >
        <p style="font-size:20px;font-weight:500">创建考试</p>
        <a-card :bordered="false" style="background:rgb(246,250,255)">
          <div style="vertical-align:middle;">
            <div style="width:50px;float:left;heigth:50px">
              <span
                style="font-size:35px;font-weight:500;color:rgb(190,220,253)"
                >1</span
              >
            </div>
            <div style="width:150px;heigth:50px;float:left;line-height:50px">
              <span style="font-size:18px;font-weight:500">基本信息</span>
            </div>
          </div></a-card
        >
        <a-card :bordered="false">
          <a-form-model-item ref="name" label="考试名称" prop="examName">
            <a-input style="width:300px" v-model="form.examName" />
          </a-form-model-item>
          <a-form-model-item ref="name" label="考试说明">
            <a-textarea style="width:300px" v-model="form.examDesc" />
          </a-form-model-item>
        </a-card>
        <!--step two -->
        <a-card :bordered="false" style="background:rgb(246,250,255)">
          <div style="vertical-align:middle;">
            <div style="width:50px;float:left;heigth:50px">
              <span
                style="font-size:35px;font-weight:500;color:rgb(190,220,253)"
                >2</span
              >
            </div>
            <div style="width:150px;heigth:50px;float:left;line-height:50px">
              <span style="font-size:18px;font-weight:500">考试内容</span>
            </div>
          </div></a-card
        >
        <a-card :bordered="false">
          <a-form-model-item ref="name" label="试卷名称" prop="examPaperName">
            <a-input
              style="width:300px;display:none;"
              v-model="form.examPaperName"
            />
            {{ form.examPaperName }}
            <a-button type="primary" @click="showChoiceExamPaper">
              选择试卷
            </a-button>
          </a-form-model-item>
          <a-form-model-item ref="name" label="考试班级" prop="examClasses">
            <a-input
              style="width:300px;display:none;"
              v-model="form.examClasses"
            />
            {{ form.examClasses }}
            <a-button type="primary" @click="showChoiceExamClasses">
              选择考试班级
            </a-button>
          </a-form-model-item>
        </a-card>

        <!--step three -->
        <a-card :bordered="false" style="background:rgb(246,250,255)">
          <div style="vertical-align:middle;">
            <div style="width:50px;float:left;heigth:50px">
              <span
                style="font-size:35px;font-weight:500;color:rgb(190,220,253)"
                >3</span
              >
            </div>
            <div style="width:150px;heigth:50px;float:left;line-height:50px">
              <span style="font-size:18px;font-weight:500">考试设置</span>
            </div>
          </div></a-card
        >
        <a-card :bordered="false"
          ><a-form-model-item ref="name" label="总分">
            <span>{{ totalScore }}</span>
          </a-form-model-item>
          <a-form-model-item ref="name" label="通过分数" prop="examPassScore">
            <a-input
              type="number"
              style="width:100px"
              v-model="form.examPassScore"
            />
          </a-form-model-item>
          <!--  <a-form-model-item label="考试时长" prop="examTime">
            <a-radio-group v-model="form.examTime">
              <a-radio :value="0">
                不限制时长
              </a-radio>
              <a-radio :value="1">
                限制时长
              </a-radio>
            </a-radio-group>
            <a-input
              type="number"
              style="width:90px;"
              v-if="form.examTime == 1"
              v-model="form.examTimeline"
            />
          </a-form-model-item> -->
          <a-form-model-item label="开始时间" prop="examStartTime">
            <a-date-picker
              v-model="form.examStartTime"
              :disabled-date="disabledStartDate"
              show-time
              :locale="locale"
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="开始时间"
              @openChange="handleStartOpenChange"
            />
          </a-form-model-item>
          <a-form-model-item label="结束时间" prop="examEndTime">
            <a-date-picker
              v-model="form.examEndTime"
              :disabled-date="disabledEndDate"
              show-time
              :locale="locale"
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="结束时间"
              :open="endOpen"
              @openChange="handleEndOpenChange"
            />
          </a-form-model-item>
          <a-form-model-item label="答案和解析" prop="examAnswer">
            <a-radio-group v-model="form.examAnswer">
              <a-radio :value="0">
                交卷后显示
              </a-radio>
              <a-radio :value="1">
                不允许查看
              </a-radio>
              <a-radio :value="2">
                仅可查看对错
              </a-radio>
              <a-radio :value="3">
                仅可查看错题
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="防作弊设置" prop="examAntiCheat">
            <a-radio-group v-model="form.examAntiCheat">
              <a-radio :value="0">
                不设置防作弊
              </a-radio>
              <a-radio :value="1">
                试题顺序打乱
              </a-radio>
              <a-radio :value="2">
                试题选项打乱
              </a-radio>
              <a-radio :value="3">
                同时设置
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-card>
        <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button type="primary" @click="onSubmit">
            保存
          </a-button>
          <a-button style="margin-left: 10px;" @click="backCreate">
            返回
          </a-button>
        </a-form-model-item>
      </a-card>
    </a-form-model>

    <!-- 试卷选择 -->
    <a-modal
      :visible="visible"
      title="试卷选择"
      @ok="handleOk"
      @cancel="handleCancel"
      :maskClosable="false"
      :width="960"
    >
      <a-table :columns="columns" :data-source="data">
        <a slot="name" slot-scope="text">{{ text }}</a>
        <template slot="action" slot-scope="text, record">
          <a-popconfirm
            title="确认此题库?"
            ok-text="确定"
            cancel-text="取消"
            @confirm="choiceExamPaper(record)"
          >
            <a>选择</a>
          </a-popconfirm>
        </template>
      </a-table>
    </a-modal>

    <!-- 班级选择 -->
    <a-modal
      :visible="visibleClasses"
      title="班级选择"
      @ok="handleOk"
      @cancel="handleCancel"
      :maskClosable="false"
      :width="960"
    >
      <a-table :columns="columnsClasses" :data-source="dataClasses">
        <a slot="name" slot-scope="text">{{ text }}</a>
        <template slot="action" slot-scope="text, record">
          <a-popconfirm
            title="确认此班级进行考试?"
            ok-text="确定"
            cancel-text="取消"
            @confirm="choiceClass(record)"
          >
            <a>选择</a>
          </a-popconfirm>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script>
import moment from "moment";
import "moment/locale/zh-cn";
import locale from "ant-design-vue/es/date-picker/locale/zh_CN";
const columns = [
  {
    title: "题库名称",
    dataIndex: "name",
    key: "name",
    scopedSlots: { customRender: "name" }
  },
  {
    title: "题量",
    dataIndex: "countTotal",
    key: "countTotal"
  },
  {
    title: "单选",
    dataIndex: "countRadio",
    key: "countRadio"
  },
  {
    title: "多选",
    dataIndex: "countMultiSelect",
    key: "countMultiSelect"
  },
  {
    title: "判断",
    dataIndex: "countTrueOrFalse",
    key: "countTrueOrFalse"
  },
  {
    title: "填空",
    dataIndex: "countGap",
    key: "countGap"
  },
  {
    title: "问答",
    dataIndex: "countEssay",
    key: "countEssay"
  },
  {
    title: "总分",
    key: "score",
    dataIndex: "score"
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    key: "createTime"
  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "action" }
  }
];
const columnsClasses = [
  {
    title: "班级名称",
    dataIndex: "name",
    key: "name",
    scopedSlots: { customRender: "name" }
  },
  {
    title: "创建时间",
    dataIndex: "createdTime",
    key: "createdTime"
  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "action" }
  }
];
export default {
  data() {
    let checkPassScore = (rule, value, callback) => {
      if (this.totalScore === "请先选择试卷") {
        callback(new Error("请先选择试卷"));
      } else {
        if (parseInt(this.totalScore) < value) {
          callback(new Error("通过分数超过试卷总分数"));
        } else if (value < 0) {
          callback(new Error("通过分数不得小于零"));
        }
        callback();
      }
    };
    return {
      locale,
      data: [], // 选择的数据
      dataClasses: [], // 选择的数据
      information: [
        { Gap: 0, TorF: 0, Radio: 0, MultiSelect: 0, Essays: 0 }, // 每道题的数量
        { Gap: 0, TorF: 0, Radio: 0, MultiSelect: 0, Essays: 0 }, // 每道题的统一分数
        { total: 0, totalScore: 0 }
      ],
      totalScore: "请先选择试卷",
      labelCol: { span: 4 },
      wrapperCol: { span: 12 },
      other: "",
      columns,
      columnsClasses,
      form: {
        examName: "",
        examPaperName: "",
        examPaperId: "",
        examDesc: "", // 考试描述
        examPassScore: null, // 考试通过分数
        examClasses: null,
        examClassesId: null,
        examTime: null, //  是否限时
        examTimeline: 0, // 考试时长 只有限时才有效
        examStartTime: null, // 考试开放时间
        examEndTime: null, // 开始截止时间
        examAnswer: null, // 考试之后是否能查看答案
        examAntiCheat: null //  是否开启防作弊模式
      },
      post_form: {
        examName: "",
        examDesc: "",
        examPaperId: "",
        examClassesId: null,
        examSetting: {}
      },
      examSet: [],
      endOpen: false, // 日期选择器
      visible: false,
      visibleClasses: false,
      rules: {
        examName: [
          {
            required: true,
            message: "试卷名不能为空",
            trigger: "change"
          }
        ],
        examPaperName: [
          {
            required: true,
            message: "请设置考试试卷",
            trigger: "change"
          }
        ],
        examPassScore: [
          {
            required: true,
            message: "通过分数不能为空",
            trigger: "change"
          },
          { validator: checkPassScore, trigger: "change" }
        ],
        examTime: [
          {
            required: true,
            message: "请选择考试时长",
            trigger: "change"
          }
        ],
        examAnswer: [
          {
            required: true,
            message: "请选择答案和解析",
            trigger: "change"
          }
        ],
        examAntiCheat: [
          {
            required: true,
            message: "请设置考试防作弊方案",
            trigger: "change"
          }
        ],
        examStartTime: [
          {
            required: true,
            message: "请选择试卷开放开始时间",
            trigger: "change"
          }
        ],
        examEndTime: [
          {
            required: true,
            message: "请选择试卷开放截止时间",
            trigger: "change"
          }
        ],
        examClasses: [
          {
            required: true,
            message: "请选择考试班级",
            trigger: "change"
          }
        ]
      }
    };
  },

  methods: {
    onSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 名字校验通过
          this.post_form.examName = this.form.examName;
          this.post_form.examDesc = this.form.examDesc;
          this.post_form.examPaperId = this.form.examPaperId;
          this.post_form.examTime = this.form.examTime;
          this.post_form.examClassesId = this.form.examClassesId;
          this.examSet.push({
            examPassScore: this.form.examPassScore,
            examTime: this.form.examTime,
            examClasses: this.form.examClasses,
            examStartTime: new Date(
              this.form.examStartTime.format("YYYY-MM-DD HH:mm:ss")
            ),
            examEndTime: new Date(
              this.form.examEndTime.format("YYYY-MM-DD HH:mm:ss")
            ),
            examAnswer: this.form.examAnswer,
            examPaperName: this.form.examPaperName,
            examAntiCheat: this.form.examAntiCheat,
            examTotalScore: this.totalScore
          });
          console.log(JSON.stringify(this.examSet));
          this.post_form.examSetting = JSON.stringify(this.examSet);
          console.log(this.post_form);
          this.$axios
            .post("/create/exam", this.post_form, {
              headers: {
                Authorization: localStorage.getItem("token")
              }
            })
            .then(res => {
              if (res.data.code == 200) {
                this.$message.success(res.data.msg);
                this.backCreate();
              } else {
                this.$message.error(res.data.msg);
              }
            });
        } else {
          return false;
        }
      });
    },
    showChoiceExamPaper() {
      // 点击选择题库之后
      this.visible = true;
    },
    showChoiceExamClasses() {
      // 点击选择题库之后
      this.getClasses();
      this.visibleClasses = true;
    },
    handleOk(e) {
      this.visible = false;
      this.visibleClasses = false;
    },
    handleCancel(e) {
      this.visible = false;
      this.visibleClasses = false;
    },
    backCreate() {
      this.$router.push({ path: "/home/exam/examinationManagement" });
    },
    disabledStartDate(startValue) {
      const endValue = this.form.examEndTime;
      if (!startValue || !endValue) {
        return false;
      }
      return startValue.valueOf() > endValue.valueOf();
    },
    disabledEndDate(endValue) {
      const startValue = this.form.examStartTime;
      if (!endValue || !startValue) {
        return false;
      }
      return startValue.valueOf() >= endValue.valueOf();
    },
    handleStartOpenChange(open) {
      if (!open) {
        this.endOpen = true;
      }
    },
    handleEndOpenChange(open) {
      this.endOpen = open;
    },
    getExamPaper() {
      this.$axios
        .get("/get/testes/info", {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            this.data = res.data.data;
            // 信息预处理
            for (let i = 0; i < res.data.data.length; i++) {
              var obj = JSON.parse(res.data.data[i].testInformation);
              this.data[i].key = this.data[i].id;
              this.data[i].name = this.data[i].testName;
              this.data[i].countTotal = obj[2].total;
              this.data[i].score = obj[2].totalScore;
              this.data[i].countRadio = obj[0].Radio;
              this.data[i].countGap = obj[0].Gap;
              this.data[i].countMultiSelect = obj[0].MultiSelect;
              this.data[i].countTrueOrFalse = obj[0].TorF;
              this.data[i].countEssay = obj[0].Essays;
              this.data[i].createTime = this.data[i].createdTime.replace(
                "T",
                " "
              );
            }
          } else {
            this.$message.error("获取失败");
          }
        });
    },
    getClasses() {
      this.$axios
        .get("/get/class/noPage", {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            this.dataClasses = res.data.data;
            // console.log(res.data.data);
            for (let i in res.data.data) {
              Object.assign(this.dataClasses[i], { key: i + 1 });
            }
          } else {
            this.$message.error("获取失败");
          }
        });
    },
    choiceExamPaper(record) {
      this.form.examPaperId = record.id;
      this.form.examPaperName = record.name;
      var obj = JSON.parse(record.testInformation);
      this.totalScore = obj[2].totalScore;

      this.$refs.ruleForm.validate(valid => {});
      this.visible = false;
    },
    choiceClass(record) {
      this.form.examClassesId = record.id;
      this.form.examClasses = record.name;

      this.$refs.ruleForm.validate(valid => {});
      this.visibleClasses = false;
    }
  },
  created() {
    if (this.$route.query.record != undefined) {
      var obj = JSON.parse(this.$route.query.record);
      this.form.examName = obj.examName;
      // this.form.examPaperName = obj.,
      this.form.examPaperId = obj.examPaperId;
      this.form.examDesc = obj.examDesc; // 考试描述
      this.form.examPassScore = JSON.parse(obj.examSetting)[0].examPassScore; // 考试通过分数
      this.form.examClasses = obj.examClasses;
      this.form.examClassesId = obj.examClassesId;
      this.form.examStartTime = moment(obj.obj[0].examStartTime); // 考试开放时间
      // moment(obj.obj[0].examStartTime, moment.defaultFormat).toDate()
      this.form.examEndTime = moment(obj.obj[0].examEndTime); // 开始截止时间
      this.form.examAnswer = obj.obj[0].examAnswer; // 考试之后是否能查看答案
      this.form.examAntiCheat = obj.obj[0].examAntiCheat; //  是否开启防作弊模式
      this.totalScore = obj.obj[0].examTotalScore;
      this.form.examPaperName = obj.obj[0].examPaperName;
      this.post_form.id = obj.id;
      console.log(this.form);
    }
    this.getExamPaper();
  }
};
</script>

<style scoped>
.demo-infinite-container {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: auto;
  padding: 8px 24px;
  height: 500px;
}
.demo-loading-container {
  position: absolute;
  bottom: 40px;
  width: 100%;
  text-align: center;
}
.ant-modal-content {
  border-radius: 0px;
}
</style>
